package com.summer.bilibili.validator.datetime;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.*;

/**
 * 时间校验，验证日期是否在指定偏移范围内
 */
public class DateTimeLimitValidator implements ConstraintValidator < DateTimeLimit, Object > {
    //
    private Set < DateTimeLimit > forbiddenValues = new HashSet <> ( );

    @Override
    public void initialize ( DateTimeLimit constraintAnnotation ) {
        forbiddenValues.add ( constraintAnnotation );
    }


    @Override
    public boolean isValid ( Object value , ConstraintValidatorContext context ) {
        if ( !(value instanceof Date) ) {
            return true;
        }
        Date date = (Date) value;
        // 遍历所有规则
        for ( DateTimeLimit rule : forbiddenValues ) {
            TimeZone tz = TimeZone.getTimeZone ( rule.timezone ( ) );
            DateTime nowInTargetTz = DateUtil.convertTimeZone ( new Date ( ) , tz );
            DateTime offset = DateUtil.offset ( nowInTargetTz , rule.unit ( ) , rule.offset ( ) );

            // 检查是否违反当前规则
            if ( rule.type ( ) == DateTimeLimit.Type.PAST ) {
                if ( offset.isBefore ( date ) ) {
                    return false; // 违反过去时间规则
                }
            } else if ( rule.type ( ) == DateTimeLimit.Type.FUTURE ) {
                if ( offset.isAfter ( date ) ) {
                    return false; // 违反未来时间规则
                }
            }
        }
        return true;
        // 通过所有规则
        /*DateTime offset = DateUtil.offset(new Date(), instance.unit(), instance.offset());
        if (instance.type() == DateTimeLimit.Type.PAST) {
            return !offset.isBefore(date);
        } else if (instance.type() == DateTimeLimit.Type.FUTURE) {
            return !offset.isAfter(date);
        }
        return true;*/
    }
}
